import NetAdapter from "../../adpapter/NetAdapter";
import { AlertManager } from "../../alert/AlertManager";
import { Common_UIPath } from "../../common/Common_Define";
import { Cfg } from "../../config/Cfg";
import { Const } from "../../config/Const";
import { MVC } from "../../framework/MVC";
import { Notifier } from "../../framework/Notifier";
import { Time } from "../../framework/Time";
import { UIManager } from "../../framework/UIManager";
import GlobalData from "../../GlobalData";
import { ModuleLauncher } from "../../launch/ModuleLauncher";
import { SdkLauncher } from "../../launch/SdkLauncher";
import { UILanuncher } from "../../launch/UILauncher";
import { ListenID } from "../../ListenID";
import DeviceManager from "../../manager/DeviceManager";
import DouyinManager from "../../manager/DouyinManager";
import { GameVoManager } from "../../manager/GameVoManager";
import LoginManager from "../../manager/LoginManager";
import { Manager } from "../../manager/Manager";
import { Util } from "../../utils/Util";
const { ccclass, property } = cc._decorator;

@ccclass
export default class LoginView extends MVC.BaseView {
  protected changeListener(enable: boolean): void {
    // throw new Error("Method not implemented.");
  }

  @property(cc.ProgressBar)
  public progress: cc.ProgressBar = null;

  @property(cc.Label)
  public text: cc.Label = null;

  @property(cc.Label)
  public progressText: cc.Label = null;

  @property(cc.Label)
  public version: cc.Label = null;

  @property(cc.Node)
  public btnHYKBLogin: cc.Node = null;

  @property(cc.Node)
  public btnDouyinLogin: cc.Node = null;

  @property(cc.Node)
  public btnWeixinLogin: cc.Node = null;

  @property(cc.Node)
  public btnLogout: cc.Node = null;

  @property(cc.Label)
  public account: cc.Label = null;

  @property(cc.Sprite)
  public sprite: cc.Sprite = null;

  @property(cc.Node)
  public canvasNode: cc.Node = null;

  @property(cc.Node)
  public appleLogin_view: cc.Node = null;

  @property(cc.Node)
  login_view: cc.Node = null;

  @property(cc.EditBox)
  login_name: cc.EditBox = null;

  @property(cc.EditBox)
  login_password: cc.EditBox = null;

  @property(cc.Node)
  register_view: cc.Node = null;

  @property(cc.EditBox)
  register_name: cc.EditBox = null;

  @property(cc.EditBox)
  register_password: cc.EditBox = null;

  @property(cc.EditBox)
  register_password_1: cc.EditBox = null;

  agent_uid = "0";
  _login: boolean = false;

  onLoad() {
    console.log("Launcher onLoad");
    cc.game.addPersistRootNode(this.node);
    DouyinManager.inst.adinit();

    Notifier.changeListener(
      true,
      ListenID.Login_Finish2,
      this.onLoginFinish,
      this
    );

    // Object.defineProperty(cc.Node.prototype, "rotation", {
    //     get() {
    //         return cc.Node.prototype.rotation;
    //     },
    //     set(value) {

    //     },
    //     enumerable: true,
    //     configurable: true,
    // });
    this.hideAllLoginBtn();
  }
  public static init() {
    // this.logininit()
  }
  // public logininit() {
  //     var _inst = this;
  //     if (DeviceManager.inst.isDouyinMiniGame || DeviceManager.inst.isAndroid || DeviceManager.inst.isIOS) {
  //         _inst.btnHYKBLogin.active = false;
  //     }

  //     if (!DeviceManager.inst.isAndroid ) {
  //         this.btnWeixinLogin.active = false;
  //     }
  //     if(DeviceManager.inst.isIOS){
  //         this.hideAllLoginBtn();
  //         this.appleLogin_view.active = true;
  //     }
  //     // this.appleLogin_view.active = true;

  //     this.isStartLoad = false;
  //     new UILanuncher();
  //     let needcheck = false;
  //     if (!needcheck) { this.startLogin(); }
  //     console.log("logininit start");
  // }
  start() {
    console.log("launcher start");
    this.version.string = "ver:" + GlobalData.inst.version;
    let canvas = cc.director.getScene().children[1];
    let node = canvas.getChildByName("bg");
    Util.resizeNode(node);
    this.isStartLoad = false;
    new UILanuncher();
    let needcheck = false;
    if (!needcheck) {
      this.startLogin();
    }
  }
  login(event: cc.Event.EventTouch, customdata: string) {
    // DouyinManager.inst.shareAndroid(this.canvasNode, this.sprite);
    // return;

    this.progress.node.active = false;
    this.text.node.active = this.progress.node.active;

    console.log("Util.isDouyinGame()", Util.isDouyinGame());
    if (Util.isDouyinGame()) {
      //抖音小游戏
      this.logindouyin();
      return;
    }

    if (Util.isIOS() && GlobalData.inst.tempHide) {
      //ios小游戏
      this.appleLogin();
      return;
    }

    let deviceType = DeviceManager.inst.deviceType;
    console.log("deviceType", deviceType);

    DeviceManager.inst.getId((id) => {
      console.log("DeviceManager.inst.getId", id);
      this.sdkLogin(customdata)
        .then((res) => {
          Util.logExt(res, "login");
          this.btnHYKBLogin.active = false;
          this.btnDouyinLogin.active = false;
          this.btnWeixinLogin.active = false;
          this.btnLogout.active = false;
          this.account.node.active = false;
          cc.sys.localStorage.setItem("logined", "1");
          cc.sys.localStorage.setItem("account", res.nickname);
          cc.sys.localStorage.setItem("login_type", customdata);

          // if (CC_DEBUG) {
          //     GlobalData.inst.showCheat = true;
          // }

          if (GlobalData.inst.useNetWork) {
            GlobalData.inst.userid = res.id;
            this.getDailiUid();

            if (customdata == "hykb") {
              NetAdapter.getUnionidApp({
                usertype: 1,
                nickname: res.nickname,
                agent_uid: this.agent_uid,
                equipment_id: id,
                equipment_type: deviceType,
              })
                .then((res) => {
                  Util.logExt(res, "好游快爆登录成功");
                  let data = this.getUserInfo(res);

                  if (data) {
                    this.parsedLoginData(data);
                    this.showLoading();
                  }
                })
                .catch((err) => {
                  Util.logExt(err, "好游快爆登录失败");
                });
            } else if (customdata == "douyin") {
              NetAdapter.nativeDouyinLogin({
                code: res.id,
                agent_uid: this.agent_uid || 0,
                equipment_id: id,
                equipment_type: deviceType,
              })
                .then((res) => {
                  Util.logExt(res, "抖音登录成功");
                  let data = this.getUserInfo(res);
                  if (data) {
                    this.parsedLoginData(data);
                    this.showLoading();
                  }
                })
                .catch((err) => {
                  Util.logExt(err, "抖音登录成功");
                });
            } else if (customdata == "weixin") {
              Util.logExt({}, "微信登录002");
              let loginParams: any = {
                code: res.id,
                equipment_id: id,
                equipment_type: deviceType,
              };
              
              if (this.agent_uid) {
                loginParams.agent_uid = this.agent_uid;
              }

              NetAdapter.nativeWeixinLogin(loginParams)
                .then((res) => {
                  Util.logExt(res, "微信登录成功");
                  let data = this.getUserInfo(res);
                  if (data) {
                    this.parsedLoginData(data);
                    this.showLoading();
                  }
                })
                .catch((err) => {
                  Util.logExt(err, "抖音登录成功");
                });
            }
          } else {
            // 无需网络登录
            this.progress.node.active = true;
            this.text.node.active = this.progress.node.active;
            let this1 = this;
            this1.loadConfig();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    });
  }

  appleLogin() {
    do {
      if (this.login_name.string == "" || this.login_password.string == "") {
        AlertManager.showNormalTips("请输入用户名和密码");
        break;
      }
      if (this.login_name.string.length < 6) {
        AlertManager.showNormalTips("用户名不能小于6位");
        break;
      }
      if (this.login_password.string.length < 6) {
        AlertManager.showNormalTips("密码不能小于6位");
        break;
      } else {
        NetAdapter.appleLogin({
          user_login: this.login_name.string,
          user_pass: this.login_password.string,
        })
          .then((res) => {
            Util.logExt(res, "登录成功！!");
            AlertManager.showNormalTips(res.msg);
            let data = this.getUserInfo(res);
            console.log("appleLogin", data);
            if (data) {
              this.appleLogin_view.active = false;
              this.parsedLoginData(data);
              this.showLoading();
            }
          })
          .catch((err) => {
            console.log(err);
            AlertManager.showNormalTips(err.msg);
          });
        break;
      }
    } while (false);
  }

  // 苹果注册按钮事件
  appleRegister() {
    do {
      if (this.register_name.string.length <= 0) {
        AlertManager.showNormalTips("请输入用户名");
        break;
      }
      if (this.register_name.string.length < 6) {
        AlertManager.showNormalTips("用户名长度不能小于6位");
      }
      if (this.register_password.string.length <= 0) {
        AlertManager.showNormalTips("请输入密码");
        break;
      }
      if (this.register_password.string.length < 6) {
        AlertManager.showNormalTips("密码长度不能小于6位");
        break;
      }
      if (this.register_password.string != this.register_password_1.string) {
        AlertManager.showNormalTips("两次密码不一致");
        break;
      } else {
        NetAdapter.appleResRegister({
          user_login: this.register_name.string,
          user_pass: this.register_password.string,
          // user_pass2: this.register_password_1.string,
        })
          .then((res) => {
            // AlertManager.showNormalTips("注册成功")
            Util.logExt(res, "注册成功!");
            // AlertManager.showNormalTips(res.msg)
            // let data = this.getUserInfo(res);

            AlertManager.showNormalTips("注册成功!");
            this.showAppleRegister();
          })
          .catch((err) => {
            console.log("appleResErr", err);
            // AlertManager.showNormalTips(err.msg)
          });
      }
    } while (false);
  }

  public isLogin: boolean = true;
  // 注册界面和登录界面互相转化
  public showAppleRegister() {
    this.isLogin = this.login_view.active;
    if (this.isLogin) {
      this.login_view.active = false;
      this.register_view.active = true;
    } else {
      this.login_view.active = true;
      this.register_view.active = false;
    }
  }

  getDailiUid() {
    //从原生剪切板获取传入id 没有默认0
    if (
      (DeviceManager.inst.isAndroid || DeviceManager.inst.isIOS) &&
      GlobalData.inst.shareagent_uid == ""
    ) {
      let __agent_uid = DeviceManager.inst.getContentFromClipboard();
      console.log("getagent_uid: ", __agent_uid);
      // 提取 "uid" 后面的数字部分
      const uid = __agent_uid.match(/uid(\d+)/)?.[1];

      if (uid && /^\d+$/.test(uid)) {
        // uid 后面的部分是数字
        const numericValue = parseInt(uid);
        console.log("数字值:", numericValue);
        this.agent_uid = numericValue.toString();
      } else {
        // uid 后面的部分不是数字
        console.log("不是数字");
        this.agent_uid = "";
      }
      GlobalData.inst.shareagent_uid = this.agent_uid;
    } else {
      this.agent_uid = "";
    }

    return this.agent_uid;
  }

  ensureImageExtension(url) {
    // Regular expression to check if URL ends with .jpg or .png
    const imageExtensionPattern = /\.(jpg|png)$/i;

    // Test if the URL ends with .jpg or .png
    if (!imageExtensionPattern.test(url)) {
      // If not, add .png to the end of the URL
      return url + "?image=.png";
    }

    // If it already ends with .jpg or .png, return the URL as is
    return url;
  }

  parsedLoginData(data: any) {
    GlobalData.inst.notice_title = data.notice_title;
    GlobalData.inst.notice_desc = data.notice_desc;
    GlobalData.inst.token = data.token;
    GlobalData.inst.user_certverify_preconsult =
      data.user_certverify_preconsult || 0;
    GlobalData.inst.id_card_no = data.id_card_no || "";
    GlobalData.inst.user_name = data.user_name || "";
    GlobalData.inst.real_name_authentication =
      data.real_name_authentication || 0;
    GlobalData.inst.zfbAuthentication = data.zfbAuthentication || 0;
    GlobalData.inst.uid = data.id;
    GlobalData.inst.user_nickname = data.user_nickname;
    GlobalData.inst.userinfo = data.dataGame || {};

    if (GlobalData.inst.uid) {
      cc.sys.localStorage.setItem(Const.LOGIN_UID, GlobalData.inst.uid);
    } else if (
      cc.sys.localStorage.getItem(Const.LOGIN_UID) &&
      GlobalData.inst.uid
    ) {
      GlobalData.inst.uid = cc.sys.localStorage.getItem(Const.LOGIN_UID);
    }
    if (GlobalData.inst.token) {
      cc.sys.localStorage.setItem(Const.LOGIN_TOKEN, GlobalData.inst.token);
    } else if (
      cc.sys.localStorage.getItem(Const.LOGIN_TOKEN) &&
      GlobalData.inst.token
    ) {
      GlobalData.inst.token = cc.sys.localStorage.getItem(Const.LOGIN_TOKEN);
    }

    GlobalData.inst.diamond = data.diamond;
    GlobalData.inst.coin = data.coin;
    GlobalData.inst.agent_uid = data.agent_uid;
    GlobalData.inst.diffbattle = Number(data.diffbattle);

    let userData = GameVoManager.getInstance.myUserVo;
    userData.nick_name = GlobalData.inst.user_nickname;
    userData.avatar_url = this.ensureImageExtension(data.avatar);
    console.log("userData.avatar_url", userData.avatar_url);
    GlobalData.inst.userinfo.avatar_url = userData.avatar_url;
    GlobalData.inst.userinfo.nick_name = userData.nick_name;
    GlobalData.inst.provincecode = data.provincecode || 0;
    // Manager.storage.setString("localUserVo", JSON.stringify(GlobalData.inst.userinfo));

    //上传给java
    if (DeviceManager.inst.isAndroid) {
      jsb.reflection.callStaticMethod(
        "com/jingyingxiaobing/blueclient/AppActivity",
        "setUserInfo",
        "(Ljava/lang/String;Ljava/lang/String;)V",
        GlobalData.inst.uid || "",
        GlobalData.inst.token || ""
      );
    } else if (DeviceManager.inst.isIOS) {
      jsb.reflection.callStaticMethod(
        "AppController",
        "setUserInfo:token:",
        GlobalData.inst.uid || "",
        GlobalData.inst.token || ""
      );
    }
  }

  private sdkLogin(
    type
  ): Promise<{ id: string; nickname: string; usertype: string }> {
    return new Promise((resolve, reject) => {
      if (DeviceManager.inst.isAndroid || DeviceManager.inst.isIOS) {
        switch (type) {
          case "hykb":
            LoginManager.inst.hykbLogin((data) => {
              Util.logExt(data, "好游快爆login callback");
              resolve({
                id: data.userid || "",
                nickname: data.nickname || "",
                usertype: data.usertype || "hykb_login",
              });
            });
            break;
          case "douyin":
            LoginManager.inst.dyLogin((data) => {
              Util.logExt(data, "抖音login callback");
              resolve({
                id: data.userid || "",
                nickname: data.nickname || "",
                usertype: data.usertype || "dy_login",
              });
            });
            break;
          case "weixin":
            LoginManager.inst.wxLogin((data) => {
              Util.logExt(data, "微信login callback");
              resolve({
                id: data.userid || "",
                nickname: data.nickname || "",
                usertype: data.usertype || "wx_login",
              });
            });
            break;
        }
      } else {
        let params = Util.parseUrlParams(window.location.href);
        let userid = params.userid;
        if (userid) {
          resolve({
            id: userid,
            nickname: params.nickname || "",
            usertype: "web_login",
          });
        } else {
          console.error("not fond userid");
          //测试用登录
          resolve({
            id: "1145141919180",
            nickname: "不是居士",
            usertype: "web_login",
          });
        }
      }
    });
  }

  private logindouyin() {
    DouyinManager.inst.login((login) => {
      console.log("DouyinManager 002login", login);
      NetAdapter.getOpenIDMiniDouYin({ code: login.login.code }).then(
        (miniRes) => {
          Util.logExt(miniRes, "抖音code兑换openid返回");
          let data = miniRes;
          if (!data) {
            Util.logExt({}, "为空 miniRes");
            return;
          }

          let userinfo = login.userInfo || {};
          let senddata = {
            openid: data.openid,
            avatar: userinfo.avatarUrl || "https://jyxb-server.ruishangkeji.cn/logo.png",
            nickname: userinfo.nickName || "匿名用户",
            // agent_uid: 0,
          };
          console.log("向服务器发送登录请求数据", senddata);
          NetAdapter.loginMiniDouYin(senddata).then(
            (getUnionidAppDouYinRes) => {
              let data = this.getUserInfo(getUnionidAppDouYinRes);
              if (data) {
                this.parsedLoginData(data);
                this.showLoading();
              }
            }
          );
        }
      );
    });
  }

  getUserInfo(res: any) {
    let { code, info } = res;
    // if (code !== 0) {
    //   Util.logExt({}, "code不等于0");
    //   return;
    // }
    let data = res;
    if (!data || Object.keys(data).length == 0) {
      Util.logExt({}, "info[0]为空");
      return;
    }
    return data;
  }

  showLoading() {
    this.progress.node.active = true;
    this.text.node.active = this.progress.node.active;
    this.scheduleOnce(() => {
      this.loadConfig();
    }, 1);
  }

  private count: number = 0;
  private downtime: number = 0.5;
  private isStartLoad: boolean = false;
  moveon() {
    try {
      if (this.text) {
        this.count %= 6;
        this.text.string = this.getString(".", this.count);
        ++this.count;
        this.downtime = 0.5;
      } else {
        this.downtime = 99999;
      }
    } catch (error) {
      this.downtime = 999999;
    }
  }

  hideAllLoginBtn() {
    this.btnDouyinLogin.active = false;
    this.btnWeixinLogin.active = false;
    this.btnHYKBLogin.active = false;
    this.btnLogout.active = false;
    this.appleLogin_view.active = false;
  }

  showLoginBtn() {
    if (DeviceManager.inst.isDouyinMiniGame) {
      this.btnDouyinLogin.active = true;
      this.btnLogout.active = false;
      this.account.node.active = false;
    } else if (DeviceManager.inst.isAndroid) {
      this.btnWeixinLogin.active = true;
      // this.btnDouyinLogin.active = true;
    } else if (DeviceManager.inst.isIOS) {
      if (GlobalData.inst.tempHide) {
        this.hideAllLoginBtn();
        this.appleLogin_view.active = true;
      } else {
        // this.btnDouyinLogin.active = true;
        this.btnWeixinLogin.active = true;
      }
    } else {
      this.btnHYKBLogin.active = true;
    }
    // this.appleLogin_view.active = true;
  }

  startLogin() {
    this.showLoginBtn();

    this.isStartLoad = true;
    this.progress.node.active = false;
    this.text.node.active = this.progress.node.active;
    let logined = cc.sys.localStorage.getItem("logined") || "0";
    let account = cc.sys.localStorage.getItem("account") || "未知用户名";
    let login_type = cc.sys.localStorage.getItem("login_type");

    Util.logExt({ logined }, "登录状态");
    if (logined == "1") {
      if (DeviceManager.inst.isAndroid && login_type == "hykb") {
        // this.btnLogout.active = true;
      } else {
        this.btnLogout.active = false;
      }
      // this.login();
      this.account.string = account;
    } else {
      this.account.string = "未登录";
      this.btnLogout.active = false;
    }
  }
  getString(str, count) {
    let newstr = "加载中";
    let a = str;
    for (let i = 0; i < count; i++) {
      a += str;
    }
    newstr += a;
    return newstr;
  }

  update(dt: number) {
    Time.update(dt);
    Manager.loader.Update(dt);
    // this._net.Update(dt);
    if (this.isStartLoad) {
      this.downtime -= dt;
      if (this.downtime <= 0) {
        this.moveon();
      }
    }
  }

  onStartGame(event) {
    event.target.getComponent(cc.Animation).stop();
    Notifier.send(ListenID.Login_Finish);
  }

  //加载配置
  async loadConfig() {
    this.progress.progress = 0;
    GameVoManager.getInstance.myUserVo.loadState = 0;
    GameVoManager.getInstance.stateVo.loadTime = new Date().valueOf();
    GameVoManager.getInstance.myUserVo.loadState = 1;
    this.showDebug();
    //在启动模块
    // new ModuleLauncher();
    // 启动SDK
    new SdkLauncher(this.progressText, this.progress, true);
  }

  showDebug() {}

  onLoginFinish() {
    this.onClose();
    UIManager.Open(Common_UIPath.MenuUI, 0, MVC.eUILayer.Panel, null);
  }
}
